<?php

namespace App\Kernel\Http;

use Hyperf\Utils\Context;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;

class Response
{
    protected $container;

    protected $response;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->response = $container->get(ResponseInterface::class);
    }

    /**
     * @param $data
     * @return PsrResponseInterface
     */
    public function json($data)
    {
        return $this->response->json($data);
    }

    /**
     * @param string $msg
     * @param array $data
     * @return PsrResponseInterface
     */
    public function success($msg='success', $data = [])
    {
        return $this->response->json([
            'code' => 1,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    /**
     * @param string $msg
     * @param int $code
     * @param array $data
     * @return PsrResponseInterface
     */
    public function error($msg = '', $data = [], $code = 0)
    {
        return $this->response->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    public function redirect($url, $status = 302)
    {
        return $this->response()
            ->withAddedHeader('Location', (string)$url)
            ->withStatus($status);
    }


    /**
     * @return \Hyperf\HttpMessage\Server\Response
     */
    public function response()
    {
        return Context::get(PsrResponseInterface::class);
    }
}